<template>
  <div class="submit-sql">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>提交SQL变更请求</span>
        </div>
      </template>

      <el-form 
        ref="formRef"
        :model="form" 
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="请求标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入请求标题"
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="数据库实例" prop="database_id">
          <el-select 
            v-model="form.database_id" 
            placeholder="请选择数据库实例"
            style="width: 400px"
          >
            <el-option
              v-for="db in databases"
              :key="db.id"
              :label="`${db.name} (${db.host}:${db.port})`"
              :value="db.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="请求类型" prop="request_type">
          <el-select 
            v-model="form.request_type" 
            placeholder="请选择请求类型"
            style="width: 200px"
          >
            <el-option label="查询" value="query" />
            <el-option label="DML变更" value="dml" />
            <el-option label="DDL变更" value="ddl" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="请求描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述此次SQL变更的目的和影响..."
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="SQL内容" prop="sql_content">
          <el-input
            v-model="form.sql_content"
            type="textarea"
            :rows="10"
            placeholder="请输入SQL语句..."
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitRequest"
            :loading="submitting"
          >
            提交请求
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 我的请求列表 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>我的SQL请求</span>
          <el-button @click="loadMyRequests" :loading="loading">刷新</el-button>
        </div>
      </template>

      <el-table :data="myRequests" border style="width: 100%">
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="request_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getRequestTypeTag(row.request_type)">
              {{ getRequestTypeText(row.request_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="database_instance.name" label="数据库" width="150" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
      </el-table>

      <div style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="loadMyRequests"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { sqlAPI } from '../../api/sql'

const formRef = ref()
const form = reactive({
  title: '',
  database_id: '',
  request_type: 'query',
  description: '',
  sql_content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入请求标题', trigger: 'blur' }
  ],
  database_id: [
    { required: true, message: '请选择数据库实例', trigger: 'change' }
  ],
  request_type: [
    { required: true, message: '请选择请求类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入请求描述', trigger: 'blur' }
  ],
  sql_content: [
    { required: true, message: '请输入SQL内容', trigger: 'blur' }
  ]
}

const databases = ref([])
const myRequests = ref([])
const submitting = ref(false)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    databases.value = response.results || response
  } catch (error) {
    console.error('加载数据库实例失败:', error)
    ElMessage.error('加载数据库实例失败')
  }
}

const submitRequest = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await sqlAPI.createSQLRequest(form)
    ElMessage.success('SQL请求提交成功')
    resetForm()
    loadMyRequests()
  } catch (error) {
    if (error.response?.data?.error) {
      ElMessage.error(error.response.data.error)
    } else {
      console.error('提交请求失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const loadMyRequests = async () => {
  loading.value = true
  try {
    const response = await sqlAPI.getSQLRequests({
      page: currentPage.value,
      page_size: pageSize.value
    })
    myRequests.value = response.results || response
    total.value = response.count || 0
  } catch (error) {
    console.error('加载请求列表失败:', error)
    ElMessage.error('加载请求列表失败')
  } finally {
    loading.value = false
  }
}

const getRequestTypeText = (type) => {
  const map = {
    query: '查询',
    dml: 'DML变更',
    ddl: 'DDL变更',
    other: '其他'
  }
  return map[type] || type
}

const getRequestTypeTag = (type) => {
  const map = {
    query: 'info',
    dml: 'warning',
    ddl: 'danger',
    other: ''
  }
  return map[type] || ''
}

const getStatusText = (status) => {
  const map = {
    pending: '待审核',
    approved: '已批准',
    rejected: '已拒绝',
    executed: '已执行',
    failed: '执行失败'
  }
  return map[status] || status
}

const getStatusTag = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    executed: 'success',
    failed: 'danger'
  }
  return map[status] || ''
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  loadDatabases()
  loadMyRequests()
})
</script>

<style scoped>
.submit-sql {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
}
</style>
